<template>
  <div class="role-management">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>角色列表</span>
          <el-button type="primary" @click="handleAdd">新增角色</el-button>
        </div>
      </template>

      <!-- 表格 -->
      <el-table :data="tableData" v-loading="loading" border>
        <el-table-column type="index" label="序号" width="60" :index="indexMethod" />
        <el-table-column prop="name" label="角色名称" min-width="150" />
        <el-table-column prop="dataScope" label="数据权限" width="120">
          <template #default="{ row }">
            <el-tag :type="row.dataScope === '1' ? 'success' : 'info'">
              {{ row.dataScope === '1' ? '全部数据权限' : '个人数据' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
            maxlength="255"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="菜单权限" prop="menuIds">
          <div class="menu-list">
            <el-checkbox-group v-model="roleForm.menuIds">
              <el-checkbox 
                v-for="menu in menuData" 
                :key="menu.id" 
                :label="menu.id"
                class="menu-checkbox"
              >
                {{ menu.name }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>
        <el-form-item label="数据权限" prop="dataScope">
          <el-select v-model="roleForm.dataScope" placeholder="请选择数据权限" style="width: 100%">
            <el-option label="全部数据权限" value="1" />
            <el-option label="个人数据" value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>


  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getRoleList, 
  addRole, 
  updateRole, 
  deleteRole,
  getRoleMenus
} from '@/api/role'
import { getMenuList } from '@/api/menu'

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const roleFormRef = ref()

// 角色表单
const roleForm = reactive({
  id: '',
  name: '',
  description: '',
  menuIds: [],
  dataScope: '1'
})

// 表单验证规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  description: [
    { max: 255, message: '备注不能超过255个字符', trigger: 'blur' }
  ],
  dataScope: [
    { required: true, message: '请选择数据权限', trigger: 'change' }
  ]
}



// 菜单数据
const menuData = ref([])
const menuProps = {
  children: 'children',
  label: 'name'
}

// 获取角色列表
const getRoleData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      name: searchForm.name
    }
    const response = await getRoleList(params)
    tableData.value = response.records || response.data || []
    pagination.total = response.total || 0
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 获取菜单权限数据
const getMenuData = async () => {
  try {
    const response = await getMenuList()
    // 显示所有一级菜单，不进行过滤
    menuData.value = (response || [])
      .filter(menu => menu.parentId === "0")
      .map(menu => ({
        ...menu,
        children: [] // 清空子菜单
      }))
  } catch (error) {
    console.error('获取菜单列表失败:', error)
  }
}

// 新增角色
const handleAdd = () => {
  dialogTitle.value = '新增角色'
  dialogVisible.value = true
  Object.assign(roleForm, {
    id: '',
    name: '',
    description: '',
    menuIds: [],
    dataScope: '1'
  })
}

// 编辑角色
const handleEdit = async (row) => {
  dialogTitle.value = '编辑角色'
  dialogVisible.value = true
  
  // 先设置基本信息
  Object.assign(roleForm, {
    id: row.id,
    name: row.name,
    description: row.remark || row.description || '', // 优先使用remark字段
    menuIds: [],
    dataScope: row.dataScope || '1'
  })
  
  try {
    // 获取该角色的菜单权限
    const menuResponse = await getRoleMenus(row.id)
    console.log('角色菜单数据:', menuResponse)
    
    // 如果返回的是菜单ID数组，直接使用
    if (Array.isArray(menuResponse)) {
      roleForm.menuIds = menuResponse
    } 
    // 如果返回的是对象，可能需要提取ID
    else if (menuResponse && Array.isArray(menuResponse.data)) {
      roleForm.menuIds = menuResponse.data
    }
    // 如果返回的是对象数组，提取ID
    else if (Array.isArray(menuResponse) && menuResponse.length > 0 && typeof menuResponse[0] === 'object') {
      roleForm.menuIds = menuResponse.map(item => item.id || item.menuId)
    }
    
    console.log('设置的角色菜单ID:', roleForm.menuIds)
  } catch (error) {
    console.error('获取角色菜单失败:', error)
    ElMessage.error('获取角色菜单失败')
  }
}

// 删除角色
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该角色吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteRole(row.id)
    ElMessage.success('删除成功')
    getRoleData()
  } catch (error) {
    if (error !== 'cancel') {
      // 显示错误信息
      ElMessage.error(error.message || '删除失败')
    }
  }
}



// 提交表单
const handleSubmit = async () => {
  try {
    await roleFormRef.value.validate()
    
    // 根据接口要求调整数据结构
    const submitData = {
      name: roleForm.name,
      remark: roleForm.description, // 添加备注字段
      dataScope: parseInt(roleForm.dataScope), // 转换为数字
      menuIds: roleForm.menuIds.map(id => parseInt(id)) // 转换为数字数组
    }
    
    console.log('提交的角色数据:', submitData)
    
    if (roleForm.id) {
      // 编辑模式，添加ID（保持字符串格式避免精度丢失）
      submitData.id = roleForm.id
      await updateRole(submitData)
      ElMessage.success('更新成功')
    } else {
      // 新增模式
      await addRole(submitData)
      ElMessage.success('新增成功')
    }
    
    dialogVisible.value = false
    getRoleData()
  } catch (error) {
    console.error('表单提交失败:', error)
    // 显示错误信息
    ElMessage.error(error.message || '操作失败')
  }
}

// 对话框关闭
const handleDialogClose = () => {
  roleFormRef.value?.resetFields()
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getRoleData()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  pagination.current = 1
  getRoleData()
}

// 每页显示条数改变
const handleSizeChange = (val) => {
  pagination.size = val
  pagination.current = 1
  getRoleData()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.current = val
  getRoleData()
}

// 序号方法
const indexMethod = (index) => {
  return (pagination.current - 1) * pagination.size + index + 1
}

// 初始化
onMounted(() => {
  getRoleData()
  getMenuData()
})
</script>

<style lang="scss" scoped>
.role-management {
  .search-card {
    margin-bottom: 20px;
  }
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    :deep(.el-table) {
      width: 100%;
      
      .el-table__body-wrapper {
        overflow-x: auto;
      }
      
      .el-table__cell {
        text-align: center !important;
      }
      
      .el-table__header {
        .el-table__cell {
          text-align: center !important;
        }
      }
    }
  }
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .menu-list {
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 15px;
    background-color: #fafafa;
    
    .menu-checkbox {
      display: inline-block;
      margin-right: 20px;
      margin-bottom: 12px;
      min-width: 120px;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
  
}
</style> 